package com.label.Service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.label.Dao.TagMapper;
import com.label.Model.Bo.TagBo;
import com.label.Model.Do.Tag;
import com.label.Model.Query.CourseInfoQuery;
import com.label.Model.Query.TagQuery;
import com.label.Service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@Transactional(rollbackFor = {Exception.class})
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements TagService {

    @Resource
    @Qualifier("oracleJdbcTemplate")
    private JdbcTemplate oracleJdbc;

    @Resource
    private TagMapper tagMapper;

    @Override
    public List<TagBo> getAllTagByCourse(CourseInfoQuery courseInfoQuery) {
        if(courseInfoQuery.getCourseInfoId()==null)
            return new ArrayList<>();
        List<Map<String,Object>> courseTags=oracleJdbc.queryForList("select tag from course_tag where course_info_id="+courseInfoQuery.getCourseInfoId());
        List<String> courseTagList=courseTags.stream().map(p->p.get("TAG").toString()).collect(Collectors.toList());
        List<Tag> tags=tagMapper.selectList(new QueryWrapper<Tag>().lambda().eq(Tag::getType,1));
        List<TagBo> tagBos= JSON.parseArray(JSON.toJSONString(tags), TagBo.class);
        tagBos.forEach(p->p.setState(0));
        Map<String,TagBo> tagBoMap=tagBos.stream().collect(Collectors.toMap(TagBo::getName, p->p, (key1, key2) -> key2));
        courseTagList.forEach(p->{if(tagBoMap.containsKey(p)){TagBo tagBo=tagBoMap.get(p);tagBo.setState(1);tagBoMap.put(p,tagBo);}});
        return new ArrayList<>(tagBoMap.values());
    }

    @Override
    public Boolean checkTagName(TagQuery tagQuery) {
        List<Tag> tags=tagMapper.selectList(new QueryWrapper<Tag>().lambda().eq(Tag::getType,1));
        List<String> tagNames=tags.stream().map(Tag::getName).collect(Collectors.toList());
        return tagNames.contains(tagQuery.getName());
    }
}
